from __future__ import division
from django.template import loader, Context
from django.http import HttpResponse
from django.shortcuts import render_to_response
from MDC.CARTOON.forms import AddCartoonForm, SearchCartoonForm, EditCartoonForm, DeleteCartoonForm
from django.views.decorators.csrf import csrf_exempt

import os,ImageFile,uuid
import settings

from MDC.CARTOON.models import Cartoon, CartoonPicture
from MDC.CARTOON.models import VFormat

import Image


def viewCartoon(request):
    cartoons = Cartoon.objects.all()
    t = loader.get_template("cartoon/viewcartoonlist.html")
    c = Context({'cartoons' : cartoons, "size":len(cartoons)})
    return HttpResponse(t.render(c))

@csrf_exempt
def addcartoon(request):

    if request.method == 'POST':
        acform = AddCartoonForm(request.POST)
        if acform.is_valid():
            cd = acform.cleaned_data
            qr = Cartoon.objects.filter(name=cd.get('name'))
            if qr.count() != 0:
                acform = AddCartoonForm(initial={"date":"2006-12-10", })
                return render_to_response('addcartoon.html', {'addResult': "Already exist.", 'form': acform, 'cartoons':qr})
            cartoon = Cartoon(
                name=cd.get('name'),
                path=cd.get('path'),
                episodeNum=cd.get('episodeNum'),
                company=cd.get('company'),
                date=cd.get('date'),
                )
            cartoon.save()
            for vf in cd.get('vFormats'):
                try:
                    vfmt = VFormat.objects.get(vFormat=vf)
                except Exception:
                    vfmt = VFormat.objects.create(vFormat=vf)
                cartoon.vFormats.add(vfmt)
                cartoon.save()
            #file = request.FILES.get("Filedata",None)
            #uploadResult = "False"
            #if file:
            #    if _upload(file, cd.name):
            #        uploadResult = "Success"
            #if uploadResult:
                #for f in file:


            #return HttpResponseRedirect('/contact/thanks/')
            results = Cartoon.objects.filter(name=cd.get('name'))
            return render_to_response('addsuccess.html', {'uploadResult':'add success', 'name':cd.get('name'), 'tname':cd.get('name'), "results":results } )
    else:
        acform = AddCartoonForm(initial={"date":"2006-12-10", })

    return render_to_response('addcartoon.html', {'form': acform})
    #return acform

@csrf_exempt
def uploadCartoonImgs(request):
    #addcartoon(request)
    response=HttpResponse()
    response['Content-Type']="text/javascript"
    tname = request.POST.get('tname')
    try:
        cartoon = Cartoon.objects.get(name=tname)
    except Exception:
        response.write("2")
        return response
    #Picture.objects.create(pic=file)
    #cartoon.pics.add()
    ret="2"
    file = request.FILES.get("Filedata",None)
    pic = CartoonPicture(pname=file.name, cartoon=cartoon)

    pic.save()

    #pic.cartoon = cartoon
    pic.save()
    try:
        pic.pic.save(file.name, file)
    except Exception, e:
        pass


    #thumbUrl = pic.getThumbUrl()
    #imgUrl = pic.getImgUrl()
    #thumbPath = os.path.join(settings.MEDIA_ROOT, thumbUrl)
    imgPath = pic.pic.path
    thumbPath = imgPath.replace("\\preview\\", "\\thumbs\\")

    thumbBuf = make_thumb(imgPath)
    thumbBuf.save(thumbPath)
    #cartoon.save()
    response.write(ret)
    return response

def make_thumb(path, size = 60, h = 40):
    pixbuf = Image.open(path)
    width, height = pixbuf.size

    if width > size:
        delta = width / size
        height2 = int(height / delta)
        if height2 > h:
            pixbuf.thumbnail((size, height2), Image.ANTIALIAS)
            pixbuf = pixbuf.crop((0,0,60,40))

        else:
            pixbuf.thumbnail((size, height2), Image.ANTIALIAS)


    else:
        pixbuf.thumbnail((width, height), Image.ANTIALIAS)

    return pixbuf

@csrf_exempt
def searchCartoon(request):
    """

    """
    if request.method == "POST":
        sform = SearchCartoonForm(request.POST)
        if sform.is_valid():
            cd = sform.cleaned_data
            name = cd.get('name')
            company = cd.get('company', None)
            date = cd.get('date', None)
            #if not (name or company or date):
            #    eform = SearchCartoonForm()
            #    return render_to_response('searchcartoon.html',{"form":eform})
            cartoons = Cartoon.objects.all()
            if name:
                cartoons = cartoons.filter(name__icontains=name)
            if company:
                cartoons = cartoons.filter(company=company)
            if date:
                cartoons = cartoons.filter(date=date)
            eform = SearchCartoonForm()
            return render_to_response("searchcartoon.html", {"results":cartoons, "form":sform})



    else:
        eform = SearchCartoonForm()
    return render_to_response('searchcartoon.html',{"form":eform})

def editCartoon(request):
    """

    """
    cid = request.path.split("/")[2]
    if request.method == "POST":
        acform = AddCartoonForm(request.POST)
        if acform.is_valid():
            cd = acform.cleaned_data
            #cid = cd.get("cid")
            qr = Cartoon.objects.get(id=int(cid))
#            name = cd.get("name")
#            ep = int(cd.get("episodeNum"))
#            company = cd.get("company")
#            date = cd.get("date")
#            path = cd.get("path")
#            if name:
#                qr.name = name
            for k in cd.keys():
                if k:
                    if k == "episodeNum":
                        setattr(qr, k, int(cd.get(k)))
                    elif k == "vFormats":
                        pass
                    else:
                        setattr(qr, k, cd.get(k))
            qr.save()
            qr.vFormats = []
            for vf in cd.get('vFormats'):
                try:
                    vfmt = VFormat.objects.get(vFormat=vf)
                except Exception:
                    vfmt = VFormat.objects.create(vFormat=vf)
                qr.vFormats.add(vfmt)
                qr.save()

            return render_to_response("viewcartoon.html", {"cartoon":qr})

    else:
        cid = request.path.split("/")[2]
        qr = Cartoon.objects.get(id=int(cid))
        vformats = qr.vFormats.all()
        acform = AddCartoonForm(initial={"name":qr.name, "episodeNum":qr.episodeNum, "company":qr.company,
                                          "date":qr.date, "path":qr.path, "vFormats":vformats })
        return render_to_response("editCartoon.html", {"form":acform, "cid":qr.getId(), "name":qr.name})


def editCartoonPictures(request):
    """

    """

def deleteCartoonPre(request):
    """
    """
    cid = request.path.split("/")[2]
    qr = Cartoon.objects.get(id=int(cid))
    formats = qr.vFormats.all()
    dcform = DeleteCartoonForm(initial={"name":qr.name, "episodeNum":qr.episodeNum, "company":qr.company,
                                        "date":qr.date, "path":qr.path, "vFormats":list(formats)})
    return render_to_response("deletecartoonpre.html", {"form":dcform, "cid":cid})

def deleteCartoon(request):
    """
    Delete cartoon.
    """
    cid = request.path.split("/")[2]
    if request.method == "POST":
        qr = Cartoon.objects.get(id=int(cid))
        pics = qr.cartoonpicture_set.all()
        for pic in pics:
            path = pic.pic.path
            tpath = path.replace(u"\\preview\\", u"\\thumbs\\")
            if os.path.exists(path):
                os.remove(path)
            if os.path.exists(tpath):
                os.remove(tpath)
        qr.delete()
        return render_to_response("deleteresult.html", {"result":"Successed", "cid":cid, "name":qr.name})
    else:
        return render_to_response("deleteresult.html", {"result":"Failed", "cid":cid, "name":""})